#!/usr/local/bin/python
# -*- coding: utf-8 -*-

#################################################
# 模块功能：用于解析支付宝账单信息（老模块）
# 待ParseAliPayNew 模块开发完成后，本模块下线
##################################################

from datetime import datetime
import xlrd2 as xlrd
import VoucherDataCheck
import toolkit
from ConfigManage import addNewExpandTypeName
from data_alchemy.account_voucher_alchemy import AccountVoucherAlchemy
from data_alchemy.alipay_voucher_alchemy import AlipayVoucherAlchemy
from data_alchemy.alipay_voucher_preview_alchemy import AlipayVoucherPreviewAlchemy
from data_alchemy.alipay_bill_aclchemy import AlipayBillAlchemy
from data_alchemy.investment_flow_alchemy import InvestmentFlowAlchemy
from initLogger import logger
import initAlipayPage
from initXirrPage import FLOW_TYPE_DING_TOU


def basicInfo(table):
    '''
    函数功能：展示excel表格基本信息
    :param table:
    :return:
    '''
    row = table.nrows
    logger.debug("行：%d"%row)

    col = table.ncols
    logger.debug("列：%d"%col)

    table_list = table.row_values(rowx=0, start_colx=0, end_colx=None)
    logger.debug(table_list)

def addAlipayBillByMonth(filePath, year, month):
    '''
    函数功能：导入支付宝账单表格内容到数据库中
    :param
        filePath 文件路径
        year: 年份
        month:月份
    :return:
    '''
    workbook = xlrd.open_workbook(filePath)
    table = workbook.sheet_by_index(0)

    tradeTypeDic={}  #用于存放交易分类的字典

    for index in range(table.nrows):
        rowList = table.row_values(rowx=index, start_colx=0, end_colx=None)
        if len(rowList)< initAlipayPage.ALIPAY_BILL_COLUMN_COUNT -1:
            logger.debug("账单数据异常：%s"%str(rowList))
            continue
        destiRowList = billItemFormatConvert(rowList, initAlipayPage.ALIPAY_BILL_TYPE_2_2023)

        if destiRowList[0].rstrip()=="支出" or  \
                destiRowList[0].rstrip()=="其他" or \
                destiRowList[0].rstrip()=="不计收支":   #用于2.0版支付宝账单 2023.03.04
            middleValue=str(destiRowList[3])
            logger.debug("add record! %s"% (middleValue.rstrip()))
            dateTimeValue = xlrd.xldate_as_datetime(destiRowList[10], workbook.datemode)
            if dateTimeValue.year==year and dateTimeValue.month==month:
                #检查是否是指定月份的账单
                alipayBillAlchemy = AlipayBillAlchemy(incomeExpenses=destiRowList[0].rstrip(),
                                                  tradeObject=destiRowList[1].rstrip(),
                                                  tradeAccount=destiRowList[2].rstrip(),
                                                  tradeDescription=middleValue.rstrip(),
                                                  receiptPayType=destiRowList[4].rstrip(),
                                                  value=destiRowList[5],
                                                  tradeStatus=destiRowList[6].rstrip(),
                                                  tradeType=destiRowList[7].rstrip(),
                                                  tradeOrderNo=destiRowList[8].rstrip(),
                                                  businessOrderNo=destiRowList[9].rstrip(),
                                                  tradeDateTime=dateTimeValue
                                                  )
                alipayBillAlchemy.AddAlipayBillItem()
                tradeTypeDic[destiRowList[7].rstrip()] = 1  #记录“交易类型”信息
            #end if
        #end if
    #end for
    addNewExpandTypeName(tradeTypeDic)

def deleteAlipayBillByMonth(year, month):
    '''
    函数功能：将指定月份的支付宝账单清空
    :param year:
    :param month:
    :return:
    '''
    alipayBillAlchemy = AlipayBillAlchemy()
    alipayBillAlchemy.DelAlipayBillByMonth(2022,9)

def alipayBillToAccountVoucher(year, month):
    '''
    函数功能：将支付宝账单转换为记账凭证
    :return:
    '''
    alipayBillAlchemy = AlipayBillAlchemy()
    alipayBillInfor = alipayBillAlchemy.SearchAlipayBillByMonth(year, month)
    logger.debug(alipayBillInfor)

    for alipayBillInforItem in alipayBillInfor:

        logger.info('账单描述: %s' % alipayBillInforItem.trade_description)

        if alipayBillInforItem.trade_status=="交易关闭":
            logger.info('##&1-处理”交易关闭“账单 %s' % alipayBillInforItem.trade_description)
            alipayBillInforItem.bill_type= initAlipayPage.CLOSE_BILL_TYPE
            continue


        if alipayBillInforItem.income_expenses=="支出":
            #处理账单中“收/支”的支出项
            if alipayBillInforItem.receipt_pay_type=="花呗" :
                #处理通过“花呗”支付的账单
                logger.info('处理通过“花呗”支付的账单 %s'% alipayBillInforItem.trade_description)
                procssHuabeiBill(alipayBillInforItem)
            elif alipayBillInforItem.receipt_pay_type=="花呗&支付宝随机立减":
                #处理通过“花呗&支付宝随机立减”支付的账单
                logger.info('处理通过“花呗&支付宝随机立减”支付的账单 %s'% alipayBillInforItem.trade_description)
                procssHuabeiBill(alipayBillInforItem)

            elif alipayBillInforItem.receipt_pay_type=="余额宝":
                #处理通过“余额宝”支付的账单
                logger.info('处理通过“余额宝”支付的账单 %s' % alipayBillInforItem.trade_description)
                #####################
                processYuebaoBill(alipayBillInforItem)
            else:
                #处理异常“收/付款方式”
                logger.warning('##&2-Notice new receipt_pay_type: %s'%alipayBillInforItem.receipt_pay_type)
                alipayBillInforItem.bill_type= initAlipayPage.UNUSUAL_BILL_TYPE

        elif alipayBillInforItem.income_expenses=="其他" or \
                alipayBillInforItem.income_expenses=="不计收支":
            #处理账单中“收/支”的其他项
            if alipayBillInforItem.trade_type=="投资理财":
                #处理”交易分类“为"投资理财"的账单
                logger.info('处理”交易分类“为"投资理财"的账单 %s' % alipayBillInforItem.trade_description)
                processInvestmentFinanceBill(alipayBillInforItem)
            elif alipayBillInforItem.trade_type=="信用借还":
                #处理”交易分类“为"信用借还"的账单
                logger.info('处理”交易分类“为"信用借还"的账单 %s' % alipayBillInforItem.trade_description)
                processCreditBill(alipayBillInforItem)


            else:
                #处理异常“交易分类”
                logger.warning('##&3-Notice new trade_type %s' % alipayBillInforItem.trade_type)
                alipayBillInforItem.bill_type = initAlipayPage.UNUSUAL_BILL_TYPE

        else:
            #处理异常“收/支“
            logger.warning('##&4-Notice new income_expenses: %s' % alipayBillInforItem.income_expenses)
            alipayBillInforItem.bill_type = initAlipayPage.UNUSUAL_BILL_TYPE

        accountVoucher = AlipayVoucherPreviewAlchemy()
        accountVoucher.CommitVoucherData()
        accountVoucher.CommitVoucherData()

def procssHuabeiBill(alipayBillInforItem):
    '''
    函数功能：处理“花呗”类型账单
    增加：权属->负债->蚂蚁花呗
    减少：权属->自有->本年结余->日常->支出->XXX
    摘要：商品说明
    :return:
    '''
    logger.debug("call procssHuabeiBill function")
    summary = ("【蚂蚁花呗负债消费】%s"%alipayBillInforItem.trade_description)
    #voucherDateStr = datetime.datetime.strftime(alipayBillInforItem.trade_time, '%Y/%m/%d')
    #voucherDate = datetime.strptime(voucherDateStr, '%Y/%m/%d')
    voucherDate = alipayBillInforItem.trade_time

    # 权属增加
    ownershipIncreaseName = "权属->负债->蚂蚁花呗"
    ownershipIncreaseFloat = alipayBillInforItem.value

    ownershipDecreaseName = ("权属->自有->本年结余->日常->支出->%s"%alipayBillInforItem.trade_type)
    ownershipDecreaseFloat = alipayBillInforItem.value
    # 权属减少

    result, message = VoucherDataCheck.CheckVoucherData("",
                                                        0.0,
                                                        "",
                                                        0.0,
                                                        ownershipIncreaseName,
                                                        ownershipIncreaseFloat,
                                                        ownershipDecreaseName,
                                                        ownershipDecreaseFloat)

    if (result == False):
        # 处理数据异常，添加失败
        logger.warning("蚂蚁花呗记账凭证解析失败：%s"%alipayBillInforItem.trade_description)
        return


    accountVoucher = AlipayVoucherPreviewAlchemy(voucherDate,
                                                 voucherNo="000",
                                                 summary=summary,
                                                 propertyIncreaseName="",
                                                 propertyIncreaseValue=0.0,
                                                 propertyDecreaseName="",
                                                 propertyDecreaseValue=0.0,
                                                 ownershipIncreaseName=ownershipIncreaseName,
                                                 ownershipIncreaseValue=ownershipIncreaseFloat,
                                                 ownershipDecreaseName=ownershipDecreaseName,
                                                 ownershipDecreaseValue=ownershipDecreaseFloat,
                                                 voucherType=initAlipayPage.ALIPAY_HUABEI_VOUCHER_TYPE
                                                 )


    accountVoucher.AddVoucherItem()
    #AddInvestFlowItem(accountVoucher)  #添加投资数据流记录
    logger.info('添加账单: %s' % alipayBillInforItem.trade_description)

    return


def processYuebaoBill(alipayBillInforItem):
    '''
    函数功能：处理“余额宝”类型账单
    :return:
    备注：
    资产减少：资产->自有->货币->电子货币->支付宝
    权属减少：权属->自有->本年结余->日常->支出->XXX
    '''
    logger.debug("call processYuebaoBill function")
    summary = ("【支付宝消费支出】%s" % alipayBillInforItem.trade_description)
    voucherDate = alipayBillInforItem.trade_time

    #资产减少
    propertyDecreaseName  = "资产->自有->货币->电子货币->支付宝"
    propertyDecreaseFloat = alipayBillInforItem.value

    # 权属减少
    ownershipDecreaseName = ("权属->自有->本年结余->日常->支出->%s" % alipayBillInforItem.trade_type)
    ownershipDecreaseFloat = alipayBillInforItem.value

    result, message = VoucherDataCheck.CheckVoucherData("",
                                                        0.0,
                                                        propertyDecreaseName,
                                                        propertyDecreaseFloat,
                                                        "",
                                                        0.0,
                                                        ownershipDecreaseName,
                                                        ownershipDecreaseFloat)

    if (result == False):
        # 处理数据异常，添加失败
        logger.warning("蚂蚁花呗记账凭证解析失败：%s" % alipayBillInforItem.trade_description)
        return

    accountVoucher = AlipayVoucherPreviewAlchemy(voucherDate,
                                                 voucherNo="000",
                                                 summary=summary,
                                                 propertyIncreaseName="",
                                                 propertyIncreaseValue=0.0,
                                                 propertyDecreaseName=propertyDecreaseName,
                                                 propertyDecreaseValue=propertyDecreaseFloat,
                                                 ownershipIncreaseName="",
                                                 ownershipIncreaseValue=0.0,
                                                 ownershipDecreaseName=ownershipDecreaseName,
                                                 ownershipDecreaseValue=ownershipDecreaseFloat
                                                 )

    accountVoucher.AddVoucherItem()
    #AddInvestFlowItem(accountVoucher)  #添加投资数据流记录
    logger.info('添加账单: %s' % alipayBillInforItem.trade_description)

    return


def processInvestmentFinanceBill(alipayBillInforItem):
    '''
    函数功能；处理“投资理财”类型账单
    :return:
    '''
    logger.debug("call processInvestmentFinanceBill function")

    if alipayBillInforItem.trade_object == "华安基金管理有限公司" and alipayBillInforItem.receipt_pay_type =="余额宝":
        logger.debug('''  alipayBillInforItem.trade_object == "华安基金管理有限公司" and alipayBillInforItem.receipt_pay_type =="余额宝"  ''')
        processYuebaoEarnings(alipayBillInforItem) #处理余额宝收益
    elif alipayBillInforItem.trade_object == "蚂蚁财富-蚂蚁（杭州）基金销售有限公司" and alipayBillInforItem.trade_description =="蚂蚁财富-鹏华丰禄债券-买入":
        logger.debug('''  alipayBillInforItem.trade_object == "蚂蚁财富-蚂蚁（杭州）基金销售有限公司" and alipayBillInforItem.trade_description =="蚂蚁财富-鹏华丰禄债券-买入"  ''')
        processPengHuaBond(alipayBillInforItem)  #处理购买鹏华丰禄债券投资
    elif alipayBillInforItem.trade_object == "蚂蚁财富-蚂蚁（杭州）基金销售有限公司" and alipayBillInforItem.trade_description =="蚂蚁财富-建信中证500指数增强A-买入":
        logger.debug('''  alipayBillInforItem.trade_object == "蚂蚁财富-蚂蚁（杭州）基金销售有限公司" and alipayBillInforItem.trade_description =="蚂蚁财富-建信中证500指数增强A-买入":  ''')
        processZhongZheng500(alipayBillInforItem) #处理购买中证500证券投资
    elif alipayBillInforItem.trade_object == "蚂蚁财富-蚂蚁（杭州）基金销售有限公司" and alipayBillInforItem.trade_description =="蚂蚁财富-招商产业债券A-买入":
        logger.debug('''  alipayBillInforItem.trade_object == "蚂蚁财富-蚂蚁（杭州）基金销售有限公司" and alipayBillInforItem.trade_description =="蚂蚁财富-招商产业债券A-买入"  ''')
        processZhaoShangBond(alipayBillInforItem)  #处理购买招商债券投资
    elif alipayBillInforItem.trade_description =="余额宝-单次转入":
        logger.debug('''  alipayBillInforItem.trade_object == "余额宝" and alipayBillInforItem.trade_description =="余额宝-单次转入"   ''')
        processYuebaoInvestment(alipayBillInforItem) #资金转入余额宝进行投资
    elif alipayBillInforItem.trade_object == "招商银行" and alipayBillInforItem.trade_description == "余额宝-还贷管家转出":
        logger.debug('''  alipayBillInforItem.trade_object == "招商银行" and alipayBillInforItem.trade_description == "余额宝-还贷管家转出"  ''')
        processRepayLoanCMB(alipayBillInforItem)  #处理“还招行房贷”类型账单
    elif alipayBillInforItem.trade_object == "中国建设银行" and alipayBillInforItem.trade_description == "余额宝-还贷管家转出":
        logger.debug('''  alipayBillInforItem.trade_object == "中国建设银行" and alipayBillInforItem.trade_description == "余额宝-还贷管家转出"  ''')
        processRepayLoanCCB(alipayBillInforItem)  #处理“还建行房贷”类型账单
    elif alipayBillInforItem.trade_description =="余额宝-转出到银行卡":
        logger.debug('''  alipayBillInforItem.trade_object == "招商银行" and alipayBillInforItem.trade_description =="余额宝-转出到银行卡入"   ''')
        processTransferBank(alipayBillInforItem)  # 余额宝中的资金转到银行
    else:
        logger.warning("##&5-exception alipay bill:%s"%alipayBillInforItem.trade_description)
        alipayBillInforItem.bill_type = initAlipayPage.UNUSUAL_BILL_TYPE

def processTransferBank(alipayBillInforItem):  # 余额宝中的资金转到银行
    '''
    函数功能：处理支付宝（余额宝）中的钱转到银行操作。目前只处理转到招行
    :param alipayBillInforItem: 
    :return: 
    资产增加："资产->自有->货币->银行存款->招行"
    资产减少："资产->自有->货币->电子货币->支付宝"
    '''

    logger.debug("call processTransferBank function")

    capitalDest ="" #记录资产转账目标
    if alipayBillInforItem.receipt_pay_type.find("招商银行") != -1:
        capitalDest="招行"
    elif alipayBillInforItem.receipt_pay_type.find("工商银行") != -1:
        capitalDest = "工行"
    elif alipayBillInforItem.receipt_pay_type.find("交通银行") != -1:
        capitalDest = "交通银行"
    else:
        logger.warning("##&6-记录资产来源匹配错误：%s" % alipayBillInforItem.trade_description)
        alipayBillInforItem.bill_type = initAlipayPage.UNUSUAL_BILL_TYPE
        return

    summary = ("【转账】支付宝->%s: %s" % (alipayBillInforItem.receipt_pay_type, alipayBillInforItem.trade_description))  # 余额宝-还贷管家转出
    voucherDate = alipayBillInforItem.trade_time

    # 资产增加
    propertyIncreaseName = "资产->自有->货币->银行存款->%s" % capitalDest
    propertyIncreaseFloat = alipayBillInforItem.value

    # 资产减少
    propertyDecreaseName = "资产->自有->货币->电子货币->支付宝"
    propertyDecreaseFloat = alipayBillInforItem.value

    result, message = VoucherDataCheck.CheckVoucherData(propertyIncreaseName,
                                                        propertyIncreaseFloat,
                                                        propertyDecreaseName,
                                                        propertyDecreaseFloat,
                                                        "",
                                                        0.0,
                                                        "",
                                                        0.0)

    if (result == False):
        # 处理数据异常，添加失败
        logger.warning("资金从余额宝转入银行卡账单解析失败：%s" % alipayBillInforItem.trade_description)
        return

    accountVoucher = AlipayVoucherPreviewAlchemy(voucherDate,
                                                 voucherNo="000",
                                                 summary=summary,
                                                 propertyIncreaseName=propertyIncreaseName,
                                                 propertyIncreaseValue=propertyIncreaseFloat,
                                                 propertyDecreaseName=propertyDecreaseName,
                                                 propertyDecreaseValue=propertyDecreaseFloat,
                                                 ownershipIncreaseName="",
                                                 ownershipIncreaseValue=0.0,
                                                 ownershipDecreaseName="",
                                                 ownershipDecreaseValue=0.0
                                                 )

    accountVoucher.AddVoucherItem()
    #AddInvestFlowItem(accountVoucher)  #添加投资数据流记录
    logger.info('添加账单: %s' % alipayBillInforItem.trade_description)

    return



def processYuebaoEarnings(alipayBillInforItem):
    '''
    函数功能；处理余额宝收益
    :param alipayBillInforItem:
    :return:
    资产增加：资产->自有->货币->电子货币->支付宝"
    权属增加：权属->自有->本年结余->投资->余额宝投资
    '''
    logger.debug("call processYuebaoEarnings function")
    summary = ("【收入】余额宝收益：%s" % alipayBillInforItem.trade_description)  # 余额宝-还贷管家转出
    voucherDate = alipayBillInforItem.trade_time

    # 资产增加
    propertyIncreaseName = "资产->自有->货币->电子货币->支付宝"
    propertyIncreaseFloat = alipayBillInforItem.value

    # 权属增加
    ownershipIncreaseName = "权属->自有->本年结余->投资->余额宝投资"
    ownershipIncreaseFloat = alipayBillInforItem.value

    result, message = VoucherDataCheck.CheckVoucherData(propertyIncreaseName,
                                                        propertyIncreaseFloat,
                                                        "",
                                                        0.0,
                                                        ownershipIncreaseName,
                                                        ownershipIncreaseFloat,
                                                        "",
                                                        0.0)

    if (result == False):
        # 处理数据异常，添加失败
        logger.warning("处理“还招行房贷”类型账单解析失败：%s" % alipayBillInforItem.trade_description)
        return

    accountVoucher =AlipayVoucherPreviewAlchemy(voucherDate,
                                                voucherNo="000",
                                                summary=summary,
                                                propertyIncreaseName=propertyIncreaseName,
                                                propertyIncreaseValue=propertyIncreaseFloat,
                                                propertyDecreaseName="",
                                                propertyDecreaseValue=0.0,
                                                ownershipIncreaseName=ownershipIncreaseName,
                                                ownershipIncreaseValue=ownershipIncreaseFloat,
                                                ownershipDecreaseName="",
                                                ownershipDecreaseValue=0.0,
                                                voucherType=initAlipayPage.ALIPAY_YUEBAO_EARNINGS_VOUCHER_TYPE
                                                )

    accountVoucher.AddVoucherItem()
    #AddInvestFlowItem(accountVoucher)  #添加投资数据流记录
    logger.info('添加账单: %s' % alipayBillInforItem.trade_description)

    return

def processYuebaoInvestment(alipayBillInforItem):
    '''
    函数功能：资金转入余额宝进行投资
    :param alipayBillInforItem:
    :return:
    资产增加："资产->自有->货币->电子货币->支付宝"
    资产减少："资产->自有->货币->银行存款->招行"
    '''
    logger.debug("call processYuebaoInvestment function")


    capitalSource ="" #记录资产来源
    if alipayBillInforItem.receipt_pay_type.find("招商银行") != -1:
        capitalSource="招行"
    elif alipayBillInforItem.receipt_pay_type.find("工商银行") != -1:
        capitalSource = "工行"
    elif alipayBillInforItem.receipt_pay_type.find("交通银行") != -1:
        capitalSource = "交通银行"
    else:
        logger.warning("##&6-记录资产来源匹配错误：%s" % alipayBillInforItem.trade_description)
        alipayBillInforItem.bill_type = initAlipayPage.UNUSUAL_BILL_TYPE
        return

    summary = ("【转账】%s->支付宝: %s" % (alipayBillInforItem.receipt_pay_type, alipayBillInforItem.trade_description))  # 余额宝-还贷管家转出
    voucherDate = alipayBillInforItem.trade_time

    # 资产增加
    propertyIncreaseName = "资产->自有->货币->电子货币->支付宝"
    propertyIncreaseFloat = alipayBillInforItem.value

    # 资产减少
    propertyDecreaseName = "资产->自有->货币->银行存款->%s" % capitalSource
    propertyDecreaseFloat = alipayBillInforItem.value

    result, message = VoucherDataCheck.CheckVoucherData(propertyIncreaseName,
                                                        propertyIncreaseFloat,
                                                        propertyDecreaseName,
                                                        propertyDecreaseFloat,
                                                        "",
                                                        0.0,
                                                        "",
                                                        0.0)

    if (result == False):
        # 处理数据异常，添加失败
        logger.warning("资金转入余额宝进行投资账单解析失败：%s" % alipayBillInforItem.trade_description)
        return

    accountVoucher = AlipayVoucherPreviewAlchemy(voucherDate,
                                                 voucherNo="000",
                                                 summary=summary,
                                                 propertyIncreaseName=propertyIncreaseName,
                                                 propertyIncreaseValue=propertyIncreaseFloat,
                                                 propertyDecreaseName=propertyDecreaseName,
                                                 propertyDecreaseValue=propertyDecreaseFloat,
                                                 ownershipIncreaseName="",
                                                 ownershipIncreaseValue=0.0,
                                                 ownershipDecreaseName="",
                                                 ownershipDecreaseValue=0.0
                                                 )

    accountVoucher.AddVoucherItem()
    #AddInvestFlowItem(accountVoucher)  #添加投资数据流记录
    logger.info('添加账单: %s' % alipayBillInforItem.trade_description)

    return

def processPengHuaBond(alipayBillInforItem):
    '''
    函数功能：处理购买鹏华丰禄债券投资
    :param alipayBillInforItem:
    :return:
    资产增加：资产->投资->理财->鹏华丰禄债券基金
    资产减少：资产->自有->货币->电子货币->支付宝

    '''
    logger.debug("call processPengHuaBond function:处理“支付宝”向“鹏华丰禄债券”投资")



    summary = ("【投资】支付宝->鹏华丰禄债券" )  # 余额宝-还贷管家转出
    voucherDate = alipayBillInforItem.trade_time

    # 资产增加
    propertyIncreaseName = "资产->投资->理财->鹏华丰禄债券基金"
    propertyIncreaseFloat = alipayBillInforItem.value

    # 资产减少
    propertyDecreaseName = "资产->自有->货币->电子货币->支付宝"
    propertyDecreaseFloat = alipayBillInforItem.value

    result, message = VoucherDataCheck.CheckVoucherData(propertyIncreaseName,
                                                        propertyIncreaseFloat,
                                                        propertyDecreaseName,
                                                        propertyDecreaseFloat,
                                                        "",
                                                        0.0,
                                                        "",
                                                        0.0
                                                        )

    if (result == False):
        # 处理数据异常，添加失败
        logger.warning("余额宝资金投资鹏华丰禄债券基金账单解析失败：%s" % alipayBillInforItem.trade_description)
        return

    accountVoucher = AlipayVoucherPreviewAlchemy(voucherDate,
                                                 voucherNo="000",
                                                 summary=summary,
                                                 propertyIncreaseName=propertyIncreaseName,
                                                 propertyIncreaseValue=propertyIncreaseFloat,
                                                 propertyDecreaseName=propertyDecreaseName,
                                                 propertyDecreaseValue=propertyDecreaseFloat,
                                                 ownershipIncreaseName="",
                                                 ownershipIncreaseValue=0.0,
                                                 ownershipDecreaseName="",
                                                 ownershipDecreaseValue=0.0,
                                                 voucherType=initAlipayPage.ALIPAY_PENGHUA_BOND_VOUCHER_TYPE
                                                 )

    accountVoucher.AddVoucherItem()
    #AddInvestFlowItem(accountVoucher) #添加投资数据流记录
    logger.info('添加账单: %s' % alipayBillInforItem.trade_description)

    return

def processZhongZheng500(alipayBillInforItem):
    '''
    函数功能：处理购买中证500证券投资
    :param alipayBillInforItem:
    :return:
    资产增加：资产->自有->货币->银行存款->中证500指数增强基金
    资产减少：资产->自有->货币->电子货币->支付宝
    '''

    logger.debug("call processZhongZheng500 function:处理“支付宝”向“中证500指数增强基金”投资")

    summary = ("【投资】支付宝->中证500增强基金")  # 余额宝-还贷管家转出
    voucherDate = alipayBillInforItem.trade_time

    # 资产增加
    propertyIncreaseName = "资产->投资->理财->中证500指数增强基金"
    propertyIncreaseFloat = alipayBillInforItem.value

    # 资产减少
    propertyDecreaseName = "资产->自有->货币->电子货币->支付宝"
    propertyDecreaseFloat = alipayBillInforItem.value

    result, message = VoucherDataCheck.CheckVoucherData(propertyIncreaseName,
                                                        propertyIncreaseFloat,
                                                        propertyDecreaseName,
                                                        propertyDecreaseFloat,
                                                        "",
                                                        0.0,
                                                        "",
                                                        0.0)

    if (result == False):
        # 处理数据异常，添加失败
        logger.warning("余额宝资金投资中证500增强基金账单解析失败：%s" % alipayBillInforItem.trade_description)
        return

    accountVoucher = AlipayVoucherPreviewAlchemy(voucherDate,
                                                 voucherNo="000",
                                                 summary=summary,
                                                 propertyIncreaseName=propertyIncreaseName,
                                                 propertyIncreaseValue=propertyIncreaseFloat,
                                                 propertyDecreaseName=propertyDecreaseName,
                                                 propertyDecreaseValue=propertyDecreaseFloat,
                                                 ownershipIncreaseName="",
                                                 ownershipIncreaseValue=0.0,
                                                 ownershipDecreaseName="",
                                                 ownershipDecreaseValue=0.0
                                                 )

    accountVoucher.AddVoucherItem()
    #AddInvestFlowItem(accountVoucher)  #添加投资数据流记录
    logger.info('添加账单: %s' % alipayBillInforItem.trade_description)

    return


def processZhaoShangBond(alipayBillInforItem):
    '''
    函数功能：处理购买招商债券投资
    :param alipayBillInforItem:
    :return:
    资产增加：资产->自有->货币->电子货币->招商产业债券A基金
    资产减少：资产->自有->货币->电子货币->支付宝
    '''

    logger.debug("call processZhaoShangBond function:处理“支付宝”向“招商产业债券A基金”投资")

    summary = ("【投资】支付宝->招商产业债券A基金")  # 余额宝-还贷管家转出
    voucherDate = alipayBillInforItem.trade_time

    # 资产增加
    propertyIncreaseName = "资产->投资->理财->招商产业债券A基金"
    propertyIncreaseFloat = alipayBillInforItem.value

    # 资产减少
    propertyDecreaseName = "资产->自有->货币->电子货币->支付宝"
    propertyDecreaseFloat = alipayBillInforItem.value

    result, message = VoucherDataCheck.CheckVoucherData(propertyIncreaseName,
                                                        propertyIncreaseFloat,
                                                        propertyDecreaseName,
                                                        propertyDecreaseFloat,
                                                        "",
                                                        0.0,
                                                        "",
                                                        0.0)

    if (result == False):
        # 处理数据异常，添加失败
        logger.warning("余额宝资金投资招商产业债券A基金账单解析失败：%s" % alipayBillInforItem.trade_description)
        return

    accountVoucher = AlipayVoucherPreviewAlchemy(voucherDate,
                                                 voucherNo="000",
                                                 summary=summary,
                                                 propertyIncreaseName=propertyIncreaseName,
                                                 propertyIncreaseValue=propertyIncreaseFloat,
                                                 propertyDecreaseName=propertyDecreaseName,
                                                 propertyDecreaseValue=propertyDecreaseFloat,
                                                 ownershipIncreaseName="",
                                                 ownershipIncreaseValue=0.0,
                                                 ownershipDecreaseName="",
                                                 ownershipDecreaseValue=0.0
                                                 )

    accountVoucher.AddVoucherItem()
    #AddInvestFlowItem(accountVoucher)  #添加投资数据流记录
    logger.info('添加账单: %s' % alipayBillInforItem.trade_description)

    return


def processRepayLoanCMB(alipayBillInforItem):
    '''
    函数功能：处理“还招行房贷”类型账单
    :param alipayBillInforItem:
    :return:
    资产增加：资产->自有->货币->银行存款->招行
    资产减少：资资产->自有->货币->电子货币->支付宝
    '''
    logger.debug("call processRepayLoanCMB function")
    summary = ("【转账】支付宝->招行 %s" % alipayBillInforItem.trade_description) # 余额宝-还贷管家转出
    voucherDate = alipayBillInforItem.trade_time

    #资产增加
    propertyIncreaseName = "资产->自有->货币->银行存款->招行"
    propertyIncreaseFloat = alipayBillInforItem.value

    #资产减少
    propertyDecreaseName  = "资产->自有->货币->电子货币->支付宝"
    propertyDecreaseFloat = alipayBillInforItem.value




    result, message = VoucherDataCheck.CheckVoucherData(propertyIncreaseName,
                                                        propertyIncreaseFloat,
                                                        propertyDecreaseName,
                                                        propertyDecreaseFloat,
                                                        "",
                                                        0.0,
                                                        "",
                                                        0.0)

    if (result == False):
        # 处理数据异常，添加失败
        logger.warning("处理“还招行房贷”类型账单解析失败：%s" % alipayBillInforItem.trade_description)
        return

    accountVoucher = AlipayVoucherPreviewAlchemy(voucherDate,
                                                 voucherNo="000",
                                                 summary=summary,
                                                 propertyIncreaseName=propertyIncreaseName,
                                                 propertyIncreaseValue=propertyIncreaseFloat,
                                                 propertyDecreaseName=propertyDecreaseName,
                                                 propertyDecreaseValue=propertyDecreaseFloat,
                                                 ownershipIncreaseName="",
                                                 ownershipIncreaseValue=0.0,
                                                 ownershipDecreaseName="",
                                                 ownershipDecreaseValue=0.0
                                                 )

    accountVoucher.AddVoucherItem()
    #AddInvestFlowItem(accountVoucher)  # 添加投资数据流记录
    logger.info('添加账单: %s' % alipayBillInforItem.trade_description)

    return


def processRepayLoanCCB(alipayBillInforItem):
    '''
    函数功能：处理“还建行房贷”类型账单
    :param alipayBillInforItem:
    :return:
    资产减少：资产->自有->货币->电子货币->支付宝
    权属减少：权属->自有->本年结余->日常->支出->建行房贷
    '''

    logger.debug("call processRepayLoanCCB function")
    summary = ("【支出】还建行房贷 %s" % alipayBillInforItem.trade_description)  # 余额宝-还贷管家转出
    voucherDate = alipayBillInforItem.trade_time



    # 资产减少
    propertyDecreaseName = "资产->自有->货币->电子货币->支付宝"
    propertyDecreaseFloat = alipayBillInforItem.value

    # 权属减少
    ownershipDecreaseName = ("权属->自有->本年结余->日常->支出->建行房贷")
    ownershipDecreaseFloat = alipayBillInforItem.value

    result, message = VoucherDataCheck.CheckVoucherData("",
                                                        0.0,
                                                        propertyDecreaseName,
                                                        propertyDecreaseFloat,
                                                        "",
                                                        0.0,
                                                        ownershipDecreaseName,
                                                        ownershipDecreaseFloat)

    if (result == False):
        # 处理数据异常，添加失败
        logger.warning("处理“还建行房贷”类型账单解析失败：%s" % alipayBillInforItem.trade_description)
        return

    accountVoucher = AlipayVoucherPreviewAlchemy(voucherDate,
                                                 voucherNo="000",
                                                 summary=summary,
                                                 propertyIncreaseName="",
                                                 propertyIncreaseValue=0.0,
                                                 propertyDecreaseName=propertyDecreaseName,
                                                 propertyDecreaseValue=propertyDecreaseFloat,
                                                 ownershipIncreaseName="",
                                                 ownershipIncreaseValue=0.0,
                                                 ownershipDecreaseName=ownershipDecreaseName,
                                                 ownershipDecreaseValue=ownershipDecreaseFloat
                                                 )

    accountVoucher.AddVoucherItem()
    #AddInvestFlowItem(accountVoucher)  # 添加投资数据流记录
    logger.info('添加账单: %s' % alipayBillInforItem.trade_description)

    return


def processCreditBill(alipayBillInforItem):
    '''
    函数功能：处理“信用借还”类型账单
    :param alipayBillInforItem:
    :return:
    '''
    logger.debug("call processCreditBill function")

    if alipayBillInforItem.trade_object == "招商银行" and alipayBillInforItem.receipt_pay_type =="余额宝":
        logger.debug(''' alipayBillInforItem.trade_object == "招商银行" and alipayBillInforItem.receipt_pay_type =="余额宝" ''')
        processRepaymentCreditCard(alipayBillInforItem)
    elif alipayBillInforItem.trade_object == "花呗" and (alipayBillInforItem.receipt_pay_type =="余额宝" or alipayBillInforItem.receipt_pay_type =="账户余额&余额宝" ):
        logger.debug(''' alipayBillInforItem.trade_object == "花呗" and alipayBillInforItem.receipt_pay_type =="余额宝" ''')
        processRepaymentHuabei(alipayBillInforItem)
    else:
        logger.warning("##&7-xception alipay bill:%s"%alipayBillInforItem.trade_description)
        alipayBillInforItem.bill_type = initAlipayPage.UNUSUAL_BILL_TYPE

def processRepaymentHuabei(alipayBillInforItem):
    '''
    函数功能:处理蚂蚁花呗还款
    :param alipayBillInforItem:
    :return:
    资产钱少：资产->自有->货币->电子货币->支付宝
    权属减少：权属->负债->蚂蚁花呗
    '''
    logger.debug("call processRepaymentHuabei function")
    summary = ("【支出】%s" % alipayBillInforItem.trade_description)
    voucherDate = alipayBillInforItem.trade_time

    #资产减少
    propertyDecreaseName  = "资产->自有->货币->电子货币->支付宝"
    propertyDecreaseFloat = alipayBillInforItem.value

    # 权属减少
    ownershipDecreaseName = ("权属->负债->蚂蚁花呗")
    ownershipDecreaseFloat = alipayBillInforItem.value


    result, message = VoucherDataCheck.CheckVoucherData("",
                                                        0.0,
                                                        propertyDecreaseName,
                                                        propertyDecreaseFloat,
                                                        "",
                                                        0.0,
                                                        ownershipDecreaseName,
                                                        ownershipDecreaseFloat)

    if (result == False):
        # 处理数据异常，添加失败
        logger.warning("处理蚂蚁花呗还款解析失败：%s" % alipayBillInforItem.trade_description)
        return

    accountVoucher = AlipayVoucherPreviewAlchemy(voucherDate,
                                                 voucherNo="000",
                                                 summary=summary,
                                                 propertyIncreaseName="",
                                                 propertyIncreaseValue=0.0,
                                                 propertyDecreaseName=propertyDecreaseName,
                                                 propertyDecreaseValue=propertyDecreaseFloat,
                                                 ownershipIncreaseName="",
                                                 ownershipIncreaseValue=0.0,
                                                 ownershipDecreaseName=ownershipDecreaseName,
                                                 ownershipDecreaseValue=ownershipDecreaseFloat
                                                 )

    accountVoucher.AddVoucherItem()
    #AddInvestFlowItem(accountVoucher)  # 添加投资数据流记录
    logger.info('添加账单: %s' % alipayBillInforItem.trade_description)

    return

def processRepaymentCreditCard(alipayBillInforItem):
    '''
    函数功能：处理信用卡还款
    :param alipayBillInforItem:
    :return:
    资产钱少：资产->自有->货币->电子货币->支付宝
    权属减少：权属->负债->信用卡
    '''
    logger.debug("call processRepaymentCreditCard function")
    logger.debug("call processRepaymentHuabei function")
    summary = ("【支出】%s" % alipayBillInforItem.trade_description)
    voucherDate = alipayBillInforItem.trade_time

    #资产减少
    propertyDecreaseName  = "资产->自有->货币->电子货币->支付宝"
    propertyDecreaseFloat = alipayBillInforItem.value

    # 权属减少
    ownershipDecreaseName = ("权属->负债->信用卡")
    ownershipDecreaseFloat = alipayBillInforItem.value


    result, message = VoucherDataCheck.CheckVoucherData("",
                                                        0.0,
                                                        propertyDecreaseName,
                                                        propertyDecreaseFloat,
                                                        "",
                                                        0.0,
                                                        ownershipDecreaseName,
                                                        ownershipDecreaseFloat)

    if (result == False):
        # 处理数据异常，添加失败
        logger.warning("处理信用卡还款解析失败：%s" % alipayBillInforItem.trade_description)
        return

    accountVoucher = AlipayVoucherPreviewAlchemy(voucherDate,
                                                 voucherNo="000",
                                                 summary=summary,
                                                 propertyIncreaseName="",
                                                 propertyIncreaseValue=0.0,
                                                 propertyDecreaseName=propertyDecreaseName,
                                                 propertyDecreaseValue=propertyDecreaseFloat,
                                                 ownershipIncreaseName="",
                                                 ownershipIncreaseValue=0.0,
                                                 ownershipDecreaseName=ownershipDecreaseName,
                                                 ownershipDecreaseValue=ownershipDecreaseFloat
                                                 )

    accountVoucher.AddVoucherItem()
    #AddInvestFlowItem(accountVoucher)  # 添加投资数据流记录

    logger.info('添加账单: %s' % alipayBillInforItem.trade_description)

    return




def mergeHuabeiAlipayVoucher(year, month):
    '''
    函数功能：合并蚂蚁花呗记账凭证成一条记账凭证
    :return:
    '''
    logger.debug("call mergeHuabeiAlipayVoucher function")

    #subject = "权属->负债->蚂蚁花呗"

    startDateStr, endDateStr = toolkit.monthlyChange(year, month)
    alipayVoucherAlchemyVoucher = AlipayVoucherAlchemy()
    alipayVoucherResult = alipayVoucherAlchemyVoucher.SearchVoucherByDateAndSubject(year=year,
                                                                                    month=month,
                                                                                    ownershipIncreaseName=initAlipayPage.HUA_BEI_SUBJECT)

    totalValue=0.0
    for alipayVoucherItem in alipayVoucherResult:
        totalValue = totalValue + alipayVoucherItem.ownership_increase_value



    voucherDate = datetime.strptime(endDateStr, '%Y-%m-%d')
    if totalValue!=0:
        #蚂蚁花呗有负债
        accountVoucher = AccountVoucherAlchemy(accountDate=voucherDate,
                                                  voucherNo="000",
                                                  summary=initAlipayPage.MERGE_HUA_BEI_SUMMARY,
                                                  propertyIncreaseName="",
                                                  propertyIncreaseValue=0.0,
                                                  propertyDecreaseName="",
                                                  propertyDecreaseValue=0.0,
                                                  ownershipIncreaseName="权属->负债->蚂蚁花呗",
                                                  ownershipIncreaseValue=totalValue,
                                                  ownershipDecreaseName="权属->自有->本年结余->日常->支出->花呗消费",
                                                  ownershipDecreaseValue=totalValue)

        #accountingVoucher.ShowVoucher()
        accountVoucher.AddVoucherItem()
        AddInvestFlowItem(accountVoucher)  # 添加投资数据流记录



def mergeYuebaoEarningsVoucher(year, month):
    '''
    函数功能：合并余额宝记账凭证成一条记账凭证
    :return:
    '''
    logger.debug("call mergeYuebaoarningsVoucher function")

    startDateStr, endDateStr = toolkit.monthlyChange(year, month)
    alipayVoucherAlchemyVoucher = AlipayVoucherAlchemy()
    alipayVoucherResult = alipayVoucherAlchemyVoucher.SearchVoucherByDateAndSubject(year=year,
                                                                                    month=month,
                                                                                    ownershipIncreaseName=initAlipayPage.YU_E_BAO_SUBJECT)

    totalValue = 0.0
    for alipayVoucherItem in alipayVoucherResult:
        totalValue = totalValue + alipayVoucherItem.ownership_increase_value

    voucherDate = datetime.strptime(endDateStr, '%Y-%m-%d')
    if totalValue != 0:
        # 蚂蚁花呗有负债
        accountVoucher = AccountVoucherAlchemy(accountDate=voucherDate,
                                                  voucherNo="000",
                                                  summary=initAlipayPage.MERGE_YU_E_BAO_SUMMARY,
                                                  propertyIncreaseName="资产->自有->货币->电子货币->支付宝",
                                                  propertyIncreaseValue=totalValue,
                                                  propertyDecreaseName="",
                                                  propertyDecreaseValue=0.0,
                                                  ownershipIncreaseName="权属->自有->本年结余->投资->余额宝投资",
                                                  ownershipIncreaseValue=totalValue,
                                                  ownershipDecreaseName="",
                                                  ownershipDecreaseValue=0.0)

        #accountingVoucher.ShowVoucher()
        accountVoucher.AddVoucherItem()
        AddInvestFlowItem(accountVoucher)  # 添加投资数据流记录


def mergePengHuaBond(year, month):
    '''
    函数功能：合并鹏华基金记账凭证成一条记账凭证
    :return:
    '''
    logger.debug("call mergePengHuaBond function")


    startDateStr, endDateStr = toolkit.monthlyChange(year, month)
    alipayVoucherAlchemyVoucher = AlipayVoucherAlchemy()
    alipayVoucherResult = alipayVoucherAlchemyVoucher.SearchVoucherByDateAndSubject(year=year,
                                                                                    month=month,
                                                                                    propertyIncreaseName=initAlipayPage.PENG_HUA_SUBJECT)

    totalValue = 0.0
    for alipayVoucherItem in alipayVoucherResult:
        totalValue = totalValue + alipayVoucherItem.property_increase_value

    voucherDate = datetime.strptime(endDateStr, '%Y-%m-%d')
    if totalValue != 0:
        # 蚂蚁花呗有负债
        accountVoucher = AccountVoucherAlchemy(accountDate=voucherDate,
                                                  voucherNo="000",
                                                  summary=initAlipayPage.MERGE_PENG_HUA_SUMMARY,
                                                  propertyIncreaseName="资产->投资->理财->鹏华丰禄债券基金",
                                                  propertyIncreaseValue=totalValue,
                                                  propertyDecreaseName="资产->自有->货币->电子货币->支付宝",
                                                  propertyDecreaseValue=totalValue,
                                                  ownershipIncreaseName="",
                                                  ownershipIncreaseValue=0.0,
                                                  ownershipDecreaseName="",
                                                  ownershipDecreaseValue=0.0)

        accountVoucher.AddVoucherItem()
        AddInvestFlowItem(accountVoucher)  # 添加投资数据流记录



def mergeOtherVoucher(year, month):
    '''
    函数功能：将其他支付宝记账凭证合并如记账凭证总表
    :param year:
    :param month:
    :return:
    '''

    alipayVoucherAlchemyVoucher = AlipayVoucherAlchemy()
    alipayVoucherResult = alipayVoucherAlchemyVoucher.SearchVoucherByMonth(year=year, month=month)

    for alipayVoucherItem in alipayVoucherResult:
        if alipayVoucherItem.voucher_type==initAlipayPage.ALIPAY_GENERAL_VOUCHER_TYPE:
            accountVoucher = AccountVoucherAlchemy(accountDate=alipayVoucherItem.account_date,
                                                    voucherNo=alipayVoucherItem.voucher_no,
                                                    summary=alipayVoucherItem.summary,
                                                    propertyIncreaseName=alipayVoucherItem.property_increase_name,
                                                    propertyIncreaseValue=alipayVoucherItem.property_increase_value,
                                                    propertyDecreaseName=alipayVoucherItem.property_decrease_name,
                                                    propertyDecreaseValue=alipayVoucherItem.property_decrease_value,
                                                    ownershipIncreaseName=alipayVoucherItem.ownership_increase_name,
                                                    ownershipIncreaseValue=alipayVoucherItem.ownership_increase_value,
                                                    ownershipDecreaseName=alipayVoucherItem.ownership_decrease_name,
                                                    ownershipDecreaseValue=alipayVoucherItem.ownership_decrease_value
                                                    )
            accountVoucher.AddVoucherItem()
            AddInvestFlowItem(accountVoucher)  # 添加投资数据流记录



def billItemFormatConvert(sourceBillItem, type):
    '''
    函数功能：支付宝账单的各字段的顺序进行标准化转换
    :param sourceBillItem:
    :param type:
    :return:
    '''


    destiBillItem=['', '', '', '', '',
                   '', '', '', '', '',
                   '', ''
                   ]

    logger.debug(sourceBillItem)
    if type== initAlipayPage.ALIPAY_BILL_TYPE_1_2022:
        destiBillItem = sourceBillItem
        return destiBillItem
    elif type== initAlipayPage.ALIPAY_BILL_TYPE_2_2023:
        destiBillItem[0] = sourceBillItem[5]
        destiBillItem[1] = sourceBillItem[2]
        destiBillItem[2] = sourceBillItem[3]
        destiBillItem[3] = sourceBillItem[4]
        destiBillItem[4] = sourceBillItem[7]
        destiBillItem[5] = sourceBillItem[6]
        destiBillItem[6] = sourceBillItem[8]
        destiBillItem[7] = sourceBillItem[1]
        destiBillItem[8] = sourceBillItem[9]
        destiBillItem[9] = sourceBillItem[10]
        destiBillItem[10] = sourceBillItem[0]
        destiBillItem[11] = sourceBillItem[11]
        return destiBillItem


def  AddInvestFlowItem(accountVoucherItem):
    '''
    函数功能：基于记账凭证数据，添加投资数据流记录
    :param accountVoucherItem:
    :return:
    '''

    #logger.debug("暂缓使用！！！！")

    if (accountVoucherItem.property_increase_value != accountVoucherItem.property_decrease_value):
        # 资产增加值不等于资产减少值，不属于投资行为
        return False


    if (accountVoucherItem.property_increase_name.find("资产->投资->理财") != -1 or \
            accountVoucherItem.property_decrease_name.find("资产->投资->理财") != -1):
        # 资产增加或资产减少项中存在“资产->投资->理财”属性，的记账凭证属于投资行为，可以添加到投资数据流中
        subStringList = accountVoucherItem.property_increase_name.split("->")
        substringListLen = len(subStringList)
        investmentName = subStringList[substringListLen - 1]
        investmentFlowAlchemy = InvestmentFlowAlchemy(investmentDate=accountVoucherItem.account_date,
                                                      investmentValue=accountVoucherItem.property_increase_value,
                                                      investmentPath=accountVoucherItem.property_increase_name,
                                                      flowType=FLOW_TYPE_DING_TOU,
                                                      voucherId=accountVoucherItem.id)

        investmentFlowAlchemy.AddInvestmentItem()




def main():
    logger.debug("hello world!")
    year = 2022
    month = 9
    #deleteAlipayBillByMonth(year, month)
    #addAlipayBillByMonth('.\\file\\alipay_record_202209.xlsx', year, month)

    mergeHuabeiAlipayVoucher("2022-10-01", "2022-10-31")
    #alipayBillToAccountVoucher()



    logger.debug("game over!")

if __name__ == '__main__':
    main()